/**
 * 数据库加载工具模块
 * 包含数据库初始化和加载相关功能
 */

export async function initializeSQL() {
  try {
    if (!window.initSqlJs) {
      await loadScript('static/sql-wasm.js');
    }
    const SQL = await window.initSqlJs({
      locateFile: file => `static/${file}`
    });
    return SQL;
  } catch (error) {
    console.error('数据库引擎加载失败', error);
    throw error;
  }
}

export async function loadDefaultDatabase() {
  try {
    this.isLoading = true;
    const response = await fetch('static/db/cddb.db');
    const buffer = await response.arrayBuffer();
    await processDatabase.call(this, buffer);
  } catch (error) {
    console.error('默认数据库加载失败', error);
    throw error;
  } finally {
    this.isLoading = false;
  }
}

export async function processDatabase(arrayBuffer) {
  try {
    if (!this.SQL) {
      throw new Error('SQL.js 未初始化');
    }
    this.db = new this.SQL.Database(new Uint8Array(arrayBuffer));
  } catch (error) {
    console.error('数据库解析错误', error);
    throw error;
  }
}

async function loadScript(src) {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script');
    script.src = src;
    script.onload = resolve;
    script.onerror = reject;
    document.head.appendChild(script);
  });
}